package com.demo.config;


import com.demo.dao.PermissionRepository;
import com.demo.dao.UserRepository;
import com.demo.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

/**
 * @ClassName MyRealm
 * @Description TODO
 * @Author Windy
 * @Date 2022/9/16 19:47
 * @Version 1.0
 **/
public class MyRealm extends AuthorizingRealm {

    public String getName(){
        return this.getClass().getName();
    }
    @Autowired
    UserRepository userRepository;

    @Autowired
    PermissionRepository permissionRepository;

    /**
     * 获取登陆用户所拥有的权限
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        List<String> permissions = permissionRepository.findPermissionsByName(username);
        HashSet<String> sets = new HashSet<>(permissions);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(sets);

        return info;
    }

    /**
     * 进行登陆验证
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        //获取数据库存放的对应用户名的真正信息
        User byName = userRepository.findByName(username);
        System.out.println(byName);
        if (byName != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, byName.getPwd(), ByteSource.Util.bytes(username), getName());

            return info;
        }
        return null;
    }
}
